<template>
     <el-row>
    <el-col :span="12">
        <el-input
            v-model="filterText"
            class="w-60 mb-2"
            placeholder="请选择角色"
        />
        <el-tree
            ref="treeRef"
            style="max-width: 1000px"
            class="filter-tree"
            :data="data"
            :props="defaultProps"
            default-expand-all
            :filter-node-method="filterNode"
            @node-click="nodeclick"
        />
    </el-col>
    <el-col :span="12">
        <el-input
            v-model="filterText1"
            class="w-60 mb-2"
            placeholder="请选择菜单"
        />
        <el-tree
            ref="treeRef1"
            style="max-width: 600px"
            :data="menudata"
            show-checkbox
            node-key="id"
            :default-expanded-keys="[2, 3,5,7]"
            :props="defaultProps1"
        />
        <el-button @click="addrolemenu" type="success">保存</el-button>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
//角色树形
import { onMounted, ref, watch } from 'vue'
import { ElMessage, ElTree, type FilterNodeMethodFunction, type TreeInstance } from 'element-plus'
import axios from 'axios'
import read from '../../http/AxiosHelper';
import write from '../../http/AxiosHelper1';
onMounted(()=>{
    getrole();
    getmenu();
})
interface Tree {
  [key: string]: any
}

const filterText = ref('')
const filterText1=ref('')
const treeRef = ref<TreeInstance>()
const treeRef1 = ref<InstanceType<typeof ElTree>>()
//角色树形的数据
const defaultProps = {
  children: 'children',
  label: 'roleName',
  value:'id'
}
//用户树形的数据
const defaultProps1={
  children: 'children',
  label: 'menuName',
  value:'id'
}
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
//角色树形
const data=ref([]);
const getrole=()=>{
    read.get("/api/Role/GetRole").then(res=>{
        data.value=res.data.data;
    })
}
//菜单树形
const menudata=ref([]);
const getmenu=()=>{
    read.get("/api/Menu/GetTreeMenu").then(res=>{
        menudata.value=res.data.data;
    })
}
//分配权限
const rolemenuinfo:any=ref({
    "roleId": 0,
  "menuId": []
})
const nodeclick=(x:any)=>{
    rolemenuinfo.value.roleId=x.id;
    fanmenu();
}
const addrolemenu=()=>{
    rolemenuinfo.value.menuId=treeRef1.value?.getCheckedKeys(false);
    write.post("/api/Menu/AddRoleMenu",rolemenuinfo.value).then(res=>{
        if(res.data.code==200){
            ElMessage.success(res.data.msg);
             getrole();
             getmenu();
        }
        else{
            ElMessage.error(res.data.msg);
        }
    })
}
const fanmenu=()=>{
    read.get("/api/Menu/GetBufenMenu",{params:{Rid:rolemenuinfo.value.roleId}}).then(res=>{
        treeRef1.value?.setCheckedKeys(res.data.data,true);
    })
}
</script>

<style scoped>

</style>